import os
from flask import Flask, request, jsonify
from flask_cors import CORS  # 配置跨域
from ReadData.ReadBin import Radar
from utils.apiResponse import APIResponse
from utils.Radar_draw import plot_single_heatmap
from radarModel.radarExploration import *
from ReadData.pycinrad import getProducts
from utils.nameUtils import generate_future_npy_filenames
import sys
app = Flask(__name__)
# 开启flask
CORS(app)  # 开启跨域



def exception_handler(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        # 直接退出如果是键盘中断
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    # 记录未处理异常
    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

# 设置全局异常处理
sys.excepthook = exception_handler


# 配置类
with open('config.yaml', 'r') as file:
    config = yaml.safe_load(file)
logger = get_logger()  # 配置日志

# 处理雷达基数据
# 实现dbz保存、dbz可视化
@app.route('/handleRadarBin', methods=['POST'])
def handleRadarBin():
    radarData = request.get_json()
    filename = radarData['filename']  # 文件名称
    filepath = radarData['path']  # 基数据所在的路径名称
    logger.info('处理' + filename)
    # 解析数据 同时保存npy文件到指定目录
    radar = Radar(filepath, config['radar']['save_path'], currentName=filename)
    logger.info("保存" + filename + "可视化结果")
    # 保存图片到路径
    save_image_name = os.path.join(config['image']['dbz']['save_path'], radar.filename + ".png")
    threading.Thread(target=plot_single_heatmap, args=(radar.dbz_data * 70, save_image_name, "png", True)).start()
    # 解析二次产品
    threading.Thread(target=getProducts, args=(filepath, config['productsPath'], filename)).start()
    return APIResponse(200, "success", save_image_name).to_json()


@app.route("/handlePredictionRadar", methods=['POST'])
def handleRadarPrediction():
    radarData = request.get_json()
    nameList = radarData.get('nameList', [])
    logger.info("准备执行雷达回波外推,加载时间戳为" + str(nameList))
    threading.Thread(target=predict_dual, args=(nameList, config)).start()
    pathList = generate_future_npy_filenames("", nameList[-1], "png", len=20)
    logger.info("预测的时间戳为" + str(pathList))
    return APIResponse(200, "success", pathList).to_json()


# @app.route("/test", methods=['POST'])
# def test():
#     result=request.get_json()
#     print(result)

if __name__ == '__main__':
    app.run(port=8090)
